package com.github.edu.repair.web.service.impl;

import com.github.admin.edu.assembly.common.entity.LayerUploadMsg;
import com.github.admin.edu.assembly.common.util.HttpFileUploadUtil;
import com.github.admin.edu.assembly.common.util.JsonUtils;
import com.github.edu.repair.web.service.UploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-8-28
 */
@Service
@Slf4j
public class UploadFileServiceImpl implements UploadFileService {


    @Value("${server.custom.static.file.upload-path}")
    private String uploadPath;

    @Override
    public String uploadLayerImage(MultipartHttpServletRequest request) {

        MultipartFile multipartFile=request.getFile("file");
        String oldFileName=multipartFile.getOriginalFilename();
        try {
            LayerUploadMsg message=new LayerUploadMsg();
            String newFileName= HttpFileUploadUtil.uploadUtil(multipartFile.getInputStream(),uploadPath,oldFileName);
            if(StringUtils.isNotBlank(newFileName)){
                Map<String,String> map=new HashMap<>();
                map.put("src","/uc/static/file/"+newFileName);
                message.setData(map);
                message.setMsg("上传成功！");
            }else {
                message.setMsg("上传失败！");
                message.setCode(1);
            }
            String msg= JsonUtils.toJson(message);
            return msg;
        } catch (IOException e) {
            log.error("获取输入流错误！");
            e.printStackTrace();
        }
        return null;
    }
}
